package com.platform.utils;

import com.google.common.base.Strings;
import com.platform.comm.util.CryptUtil;
import com.platform.comm.util.IdCardUtil;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Description: 正则验证
 *
 * @author wxw
 * @version 1.0
 * @date 2021-09-16
 **/
public class RegExValidator {
    private static final Pattern ID_CARD_PATTERN = Pattern.compile(".*?((\\b([1-9]\\d{7}((0\\d)|(1[012]))(([012]\\d)|3[01])\\d{3})(?!\\w))|([1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[012]))(([012]\\d)|3[01])\\d{3}([0-9]|x|X))).*?");
    private static final Pattern MOBILE_PATTERN = Pattern.compile(".*?(((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[0135678])|(18[0,5-9]))\\d{8}(?!\\w)).*?");

    /**
     * 验证身份证
     *
     * @param text 响应内容
     * @return boolean
     */
    public static boolean checkIdCodeForSys(String text) {
        if (Strings.isNullOrEmpty(text)) {
            return true;
        }
        boolean flag = false;
        if (text.length() > 18) {
            text = CryptUtil.bs64DecryptWithHead(text);
        }
        Matcher matcher = ID_CARD_PATTERN.matcher(text);
        boolean hasFind = matcher.find();
        while (hasFind) {
            flag = IdCardUtil.isValidatedAllIdCard(matcher.group(1));
            if (flag) {
                return true;
            }
            hasFind = matcher.find();
        }
        return false;
    }

    /**
     * 检查手机号
     *
     * @param text 响应内容
     * @return boolean
     */
    public static String checkMobileForSys(String text) {
        String message = null;
        if (Strings.isNullOrEmpty(text)) {
            return message;
        }
        Matcher matcher = MOBILE_PATTERN.matcher(text);
        if (matcher.find()) {
            String group = matcher.group(1);
            return "检测到提交内容中包含敏感信息：手机号" + group + "，请修改后再提交\n" +
                    "\n" +
                    "(请按照XXX-XXXX-XXXX的格式修改)";
        }
        return message;
    }

}
